//
//  YXMyMachineView.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/23.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXMyMachineView.h"
#import "YXMachineMenuView.h"
#import "YXMachineCell.h"
#import "YXMachinesBottomView.h"
#import "YXMachinesDropMenuView.h"
#import "YXHomeViewModel.h"
@interface YXMyMachineView ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UIView *contentView;
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) UILabel *numberLab;
@property (nonatomic ,strong) UIButton *allotBtn;
@property (nonatomic ,strong) YXMachinesDropMenuView *dropView;
@property (nonatomic ,strong) YXMachinesBottomView *bottomView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) NSString *pageNo;
@property (nonatomic ,assign) BOOL isUp; // YES:上拉 NO:下拉
@property (nonatomic ,strong) NSMutableArray *nameArr;
@end
@implementation YXMyMachineView

- (NSMutableArray *)nameArr {
    if (!_nameArr) {
        _nameArr = [NSMutableArray array];
    }
    return _nameArr;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (UILabel *)numberLab {
    if (!_numberLab) {
        _numberLab = [UILabel setLabelWithText:@"(共计0条)" fontSize:15 color:color_textOne];
        _numberLab.frame = CGRectMake(_contentView.X + 10, _contentView.H - 40, 200, 20);
    }
    return _numberLab;
}
- (UIButton *)allotBtn {
    if (!_allotBtn) {
        _allotBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _allotBtn.frame = CGRectMake(_contentView.W - 100,  _contentView.H - 60, 80, 40);
        [_allotBtn setTitle:@"分配" forState:(UIControlStateNormal)];
        [_allotBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _allotBtn.backgroundColor = color_globalColor;
        _allotBtn.layer.masksToBounds = YES;
        _allotBtn.layer.cornerRadius = 12.0f;
        [_allotBtn addTarget:self action:@selector(allotBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _allotBtn;
}

- (void)allotBtnAction:(UIButton *)sender {
 
    if (self.dropView.starTF.text.length == 0 || self.dropView.endTF.text.length == 0) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入结束编号" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *alert = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertAction *alert1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:alert];
        [alertController addAction:alert1];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
        
    }else {
        [UIView animateWithDuration:0.5 animations:^{
            self.bottomView.frame = CGRectMake(0, kScreenHeight - 364, kScreenWidth, 300);
        }];
    }
  
 
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:(CGRectMake(10, 60, kScreenWidth -20, kScreenHeight - 70 - 64))];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.cornerRadius = 20.0f;
        _contentView.layer.borderColor = color_lineColor.CGColor;
        _contentView.layer.borderWidth = 1.0f;
    }
     return _contentView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:(CGRectMake(0, 50, _contentView.frame.size.width , 400)) style:(UITableViewStylePlain)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;

    }
    return _tableView;
}

- (YXMachinesDropMenuView *)dropView {
    if (!_dropView) {
        _dropView = [[YXMachinesDropMenuView alloc] initWithFrame:(CGRectMake(0, 50, kScreenWidth, kScreenHeight))];
    }
    return _dropView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = color_backColor;
        self.pageNo = @"1";
        self.isUp = NO;
        [self requestData];
        [self createHeaderUI];
        [self createContentUI];
        [self createBottomUI];
        [self addRefresh];

    }
    return self;
}

// 添加上拉加载和下拉刷新
- (void)addRefresh {
    
    // 添加下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新的时候, 将请求的offset改为0
        self.pageNo = @"1";
        // 请求数据
        [self requestData];
        _isUp = NO; // 标识下拉
    }];
    
    // 添加上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self.tableView.mj_footer endRefreshing];
        
        // 上拉加载时, 将当前请求的页数加1
        NSInteger pageNo = [self.pageNo integerValue];
        pageNo ++;
        self.pageNo = [NSString stringWithFormat:@"%ld",pageNo];
        // 请求数据
        [self requestData];
        _isUp = YES; // 标识下拉
    }];
}

- (void)requestData{
    
    [YXHomeViewModel getQueryGetTerminalsModel:@"" pageNo:self.pageNo state:@"1" startTerminalCode:@"" endTerminalCode:@"" ModelList:^(NSArray *listArr,NSString *totalCount) {
//        NSLog(@"%@%@",listArr,totalCount);
        self.dataArr = [NSMutableArray arrayWithArray:listArr];
        self.numberLab.text = [NSString stringWithFormat:@"(共计%@条)",totalCount];
        if (listArr.count < 20) {
            self.tableView.mj_footer.hidden = YES;
        }else {
            self.tableView.mj_footer.hidden = NO;
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    } Failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showAlertWithTitle:@"提示" Message:@"维护中，请稍等！"];
    }];
    
}

- (void)createHeaderUI {

    YXMachineMenuView *menuView = [[YXMachineMenuView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 50)) withTieleArr:@[@"编号查询",@"机具筛选",@"状态筛选"]];
    [self addSubview:menuView];
    
    [menuView setSelectBtnClick:^(NSInteger index) {
        [self.dropView removeFromSuperview];
        if (index == 0) { // 编号查询
            self.dropView.type = 0;
            self.dropView.alpha = 1;
            [self addSubview:self.dropView];
            
            // 点击查询按钮
            YXWeakSelf
            [self.dropView setClickCodeSearchBtnBlock:^(NSString *starStr, NSString *endStr) {
                [YXHomeViewModel getQueryGetTerminalsModel:@"" pageNo:@"1" state:@"1" startTerminalCode:starStr endTerminalCode:endStr ModelList:^(NSArray *listArr,NSString *totalCount) {
//                    NSLog(@"%@",listArr);
                    weakSelf.dataArr = [NSMutableArray arrayWithArray:listArr];
                    weakSelf.numberLab.text = [NSString stringWithFormat:@"(共计%@条)",totalCount];
                    if (listArr.count < 20) {
                        weakSelf.tableView.mj_footer.hidden = YES;
                    }else {
                        weakSelf.tableView.mj_footer.hidden = NO;
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                    [weakSelf.tableView reloadData];
                } Failure:^(NSError *error) {
                    [weakSelf showAlertWithTitle:@"提示" Message:@"维护中，请稍等！"];
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView.mj_footer endRefreshing];
                }];
            }];
            

            
        }else if (index == 1) {  // 机具筛选
            self.dropView.type = 1;
            self.dropView.alpha = 1;
            [self addSubview:self.dropView];
            
            // 点击查询按钮
            YXWeakSelf
            [self.dropView setClickModelSearchBtnBlock:^(NSString *modelStr) {
                [YXHomeViewModel getQueryGetTerminalsModel:modelStr pageNo:@"1" state:@"1" startTerminalCode:weakSelf.dropView.starTF.text endTerminalCode:weakSelf.dropView.endTF.text ModelList:^(NSArray *listArr,NSString *totalCount) {
//                    NSLog(@"%@",listArr);
                    weakSelf.dataArr = [NSMutableArray arrayWithArray:listArr];
                    weakSelf.numberLab.text = [NSString stringWithFormat:@"(共计%@条)",totalCount];
                    if (listArr.count < 20) {
                        weakSelf.tableView.mj_footer.hidden = YES;
                    }else {
                        weakSelf.tableView.mj_footer.hidden = NO;
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                    [weakSelf.tableView reloadData];
                } Failure:^(NSError *error) {
                    [weakSelf showAlertWithTitle:@"提示" Message:@"维护中，请稍等！"];
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView.mj_footer endRefreshing];
                }];
            }];
            
        }else { // 状态筛选
            self.dropView.type = 2;
            self.dropView.alpha = 1;
            [self addSubview:self.dropView];
            
            // 点击查询按钮
            YXWeakSelf
            [self.dropView setClickStateSearchBtnBlock:^(NSString *stateStr) {
                [YXHomeViewModel getQueryGetTerminalsModel:weakSelf.dropView.typeTF.text pageNo:@"1" state:stateStr startTerminalCode:weakSelf.dropView.starTF.text endTerminalCode:weakSelf.dropView.endTF.text ModelList:^(NSArray *listArr,NSString *totalCount) {
//                    NSLog(@"%@",listArr);
                    weakSelf.dataArr = [NSMutableArray arrayWithArray:listArr];
                    weakSelf.numberLab.text = [NSString stringWithFormat:@"(共计%@条)",totalCount];
                    if (listArr.count < 20) {
                        weakSelf.tableView.mj_footer.hidden = YES;
                    }else {
                        weakSelf.tableView.mj_footer.hidden = NO;
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                    [weakSelf.tableView reloadData];
                } Failure:^(NSError *error) {
                    [weakSelf showAlertWithTitle:@"提示" Message:@"维护中，请稍等！"];
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView.mj_footer endRefreshing];
                }];
            }];
            
        }
     
    }];
}

- (void)createContentUI {
    [self addSubview:self.contentView];
    [self.contentView addSubview:[self createSectionView]];
    [self.contentView addSubview:self.tableView];
    [self.contentView addSubview:self.numberLab];
    [self.contentView addSubview:self.allotBtn];
    
}

- (void)createBottomUI {
    self.bottomView = [[YXMachinesBottomView alloc] initWithFrame:(CGRectMake(0, kScreenHeight, kScreenWidth, 300)) withDataArray:nil];
    [self addSubview:self.bottomView];
    [YXHomeViewModel getQueryGetMeAndNextAgentsSessionId:[YXUserInfoManager getUserInfo].sessionId ModelList:^(NSArray *listArr) {
        self.bottomView.listArr =listArr;
        for (YXUserInfoModel *model in listArr) {
            [self.nameArr addObject:model.name];
        }
        
    } Failure:^(NSError *error) {
        [self showAlertWithTitle:@"提示" Message:@"维护中，请稍等！"];
    }];
    
    
    // 点击确定
    YXWeakSelf
    [self.bottomView setSelectBtnClickBlock:^(NSString *agentid){
        
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.bottomView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 300);
        }];
        
        [YXHomeViewModel getQueryAllotTerminalsSessionId:[YXUserInfoManager getUserInfo].sessionId startTerminalCode:weakSelf.dropView.starTF.text endTerminalCode:weakSelf.dropView.endTF.text agentid:agentid == nil ? @"" : agentid ModelList:^(NSArray *listArr) {
            [weakSelf showAlertWithTitle:@"提示" Message:@"分配成功！"];
        
        } Failure:^(NSError *error) {
            [weakSelf showAlertWithTitle:@"提示" Message:@"维护中，请稍等！"];
        }];
        
      
       
    }];
    
    // 输入手机号码
    [self.bottomView setInputPhoneNumber:^(NSString *phone) {
        //获取验证码
        NSString *str = [weakSelf valiMobile:phone];
        
        if(str) {
            [weakSelf showTostMessage:str];
        }else {
            //    http://121.196.210.134:8082/mpos/wx/findNextAgentByPhone.do?sessionId=5d7465e3-82fc-4926-92d7-4b78f10d1201&phone=18652070598
            NSString *urlStr = @"findNextAgentByPhone.do";
            NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"phone":phone};
            
            [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
//                NSLog(@"%@",responseObject);
                YXUserInfoModel *model = [YXUserInfoModel mj_objectWithKeyValues:responseObject[@"body"]];
                if ([weakSelf.nameArr containsObject:model.name]) {
                    NSInteger index = [weakSelf.nameArr indexOfObject:model.name];
                    weakSelf.bottomView.index = @(index).stringValue;
                }else {
                    
                    [weakSelf showAlertWithTitle:@"提示" Message:@"未查询到此人！"];
                }
                
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [weakSelf showAlertWithTitle:@"提示" Message:@"号码错误，请重新输入电话号码！"];
            }];
            
        }
    }];
    
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * cellId = @"YXMachineCell";
    YXMachineCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell==nil) {
        cell=[[[NSBundle mainBundle]loadNibNamed:cellId owner:self options:nil] lastObject];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    cell.model = self.dataArr[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

- (UIView *)createSectionView {
    UIView *sectionView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, self.contentView.W, 50))];
    sectionView.backgroundColor = [UIColor whiteColor];
    NSArray *arr = @[@"机具编号",@"机具类型",@"状态"];
    for (int i = 0 ; i < arr.count; i ++) {
        UILabel *lab = [UILabel setLabelWithText:arr[i] fontSize:16 color:color_textOne];
        lab.frame = CGRectMake(sectionView.W / arr.count * i, 0, sectionView.W / 3, 50);
        lab.textAlignment = NSTextAlignmentCenter;
        [sectionView addSubview:lab];
    }
    UIView *lineView = [[UIView alloc] initWithFrame:(CGRectMake(10, sectionView.H - 1, _contentView.W - 20, 1))];
    lineView.backgroundColor = color_lineColor;
    [sectionView addSubview:lineView];
    return sectionView;
}


@end
